import Vue from "vue"

function gData({
	globalData={},
	setLongStorageData=[],
	actionMap={}
}) {



	let saveGlobalData = uni.getStorageSync("$$globalData") || {}
	Object.assign(globalData, saveGlobalData)

	const _vm = new Vue({
		data: {
			$$globalData: globalData
		},
		computed: {
			...setComputdeMapState()
		},
	})

	const $$globalData = _vm._data.$$globalData

	const saveLifeData = function(key, value) {
		if (setLongStorageData.indexOf(key) !== -1) {
			let tmp = uni.getStorageSync('$$globalData') || {}
			tmp[key] = value;
			uni.setStorageSync('$$globalData', tmp);
		}
	}

	function $gSet(propertyName, value) {
		let propertyValue = $$globalData
		let nameArr = propertyName.split('.');
		let nameArrEnd = nameArr.pop()
		nameArr.forEach(item => propertyValue = propertyValue[item])
		let key = nameArr.shift() || nameArrEnd
		_vm.$set(propertyValue, nameArrEnd, value)
		saveLifeData(key, $$globalData[key])
		return _vm;
	}
	Vue.prototype.$gSet = $gSet
	Vue.prototype.$gData = _vm

	function setComputdeMapState(keys = Object.keys(globalData)) {
		let arrFunc = {}
		keys.forEach(initMapState)

		function initMapState(key) {
			arrFunc[key] = {
				get: function() {
					if (actionMap[key]) $gSet(key, action())
					return $$globalData[key]
				},
				set: function(val) {
					saveLifeData(key, val)
					return $$globalData[key] = val
				}
			}
			let action = () => actionMap[key].call(_vm, $$globalData[key], data => $gSet(key, data)) || $$globalData[
				key]
		}
		return arrFunc
	}

	Vue.mixin({
		computed: {
			...setComputdeMapState()
		}
	})
}

export default{
	gData
}